// define angular module/app
var userApp = angular.module('userApp', ['ajoslin.promise-tracker']);

userApp.directive('match',['$parse', function ($parse) {
    return {
        require: 'ngModel',
        restrict: 'A',
        link: function(scope, elem, attrs, ctrl) {
//This part does the matching
            scope.$watch(function() {
                return (ctrl.$pristine && angular.isUndefined(ctrl.$modelValue)) || $parse(attrs.match)(scope) === ctrl.$modelValue;
            }, function(currentValue) {
                ctrl.$setValidity('match', currentValue);
            });

//This part is supposed to check the strength
            /*
            ctrl.$parsers.unshift(function(viewValue) {
                var pwdValidLength, pwdHasLetter, pwdHasNumber;

                pwdValidLength = (viewValue && viewValue.length >= 6 ? true : false);
                pwdHasLetter = (viewValue && /[A-z]/.test(viewValue)) ? true : false;
                pwdHasNumber = (viewValue && /\d/.test(viewValue)) ? true : false;

                if( pwdValidLength && pwdHasLetter && pwdHasNumber ) {
                    ctrl.$setValidity('pwd', true);
                } else {
                    ctrl.$setValidity('pwd', false);                    
                }
                return viewValue;
            });*/
        },
    };
}]);


userApp.controller('signupController' , function signupController($scope , $http , promiseTracker , $log , $timeout) {					
        // create a blank object to hold our form information
        // $scope will allow this to pass between controller and view

    $scope.signup = {};

    // process the form
    $scope.signupProcess = function( form ) {
            $scope.submitted = true;

            // If form is invalid, return and let AngularJS show validation errors.
          if ($scope.signupForm.$invalid) { console.log('signupForm = ' , $scope.signupForm);
            var field = null,
                firstError = null;
            for (field in $scope.signupForm) {
                if (field[0] != '$')
                {
                    if (firstError === null && !$scope.signupForm[field].$valid) {
                        firstError = $scope.signupForm[field].$name;
                    }

                    if ($scope.signupForm[field].$pristine) {
                        $scope.signupForm[field].$dirty = true;
                    }
                }
            }

            signupForm[firstError].focus();
            return;
          }


        if( $scope.signupForm.$valid) { 
            
            console.log('$scope.signup = ' , $scope.signup);
                //$scope.signupForm.email.$setValidity('havemail', false);
                //console.log('$scope.signupForm = ' , $scope.signupForm);
                //$scope.signupForm.name.$setValidity('invalid' , false);
                //$scope.signupForm.name.$invalid = data.errors.user.name;
                //$scope.errorSuperhero = data.errors.superheroAlias;
                //return false;

                //$scope.loading = true;
                //$scope.submit = false;
                $scope.loadingTracker = promiseTracker('loadingTracker');

          //use `addPromise` to add any old promise to our tracker
            $scope.delaySomething = function() {
                var promise = $timeout(function() {
                alert('Delayed something!');
                }, 1000);
                $scope.loadingTracker.addPromise(promise);
            };

            

            $http({
                method  : 'POST',
                url     : base_url + 'users/create' ,
                data    : $.param($scope.signup),  // pass in data as strings
                headers : { 'Content-Type': 'application/x-www-form-urlencoded' } ,  // set the headers so angular passing info as form data (not request payload)
                tracker: $scope.loadingTracker 
                } )
                .success(function(data) {
                    console.log(data);

                    if (!data.success) {
                        // if not successful, bind errors to error variables
                        console.log('field = ' , data.name_error);
                        angular.forEach(data.name_error, function(value) {
                            field = value.field;
                            ngshow_error = value.ngshow;
                            $scope.signupForm[field].$dirty = true;
                            $scope.signupForm[field].$setValidity(ngshow_error , false);
                        })
                        signupForm[data.name_error[0].field].focus();
                    } 
                    else {
                        // if successful, bind success message to message
                        $scope.message = data.message;
                        
                    }
            });

        }
        else{ 
            console.log('Errors in form data');
            $scope.signupForm.name.$setValidity('required', false);
        }
    };

});
